package login

import (
	"context"
	"crypto/md5"
	"demo/api/backend/login"
	"demo/internal/consts"
	"demo/internal/dao"
	"demo/internal/model/entity"
	"demo/internal/service"
	"demo/library/liberr"
	"encoding/hex"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
)

func init() {
	service.RegisterLogin(New())
}
func New() *sLogin {
	return &sLogin{}
}

type sLogin struct {
}

func (s *sLogin) PassLogin(ctx context.Context, req *login.LoginReq) (account *entity.Account, err error) {
	err = g.Try(ctx, func(ctx context.Context) {
		account = &entity.Account{}
		err = dao.Account.Ctx(ctx).Where(dao.Account.Columns().LoginName, req.Username).Scan(account)
		liberr.ErrIsNil(ctx, err, "账号不存在")
		liberr.ValueIsNil(account, "账号密码错误")
		hashedBytes := md5.Sum([]byte(req.Password + consts.PasswordSalt))
		checkPass := hex.EncodeToString(hashedBytes[:])
		if account.LoginPwd != checkPass {
			liberr.ErrIsNil(ctx, gerror.New("密码错误"))
		}
	})

	return account, err
}
